package com.bnz.dao.impl;

import com.bnz.dao.UserDao;
import com.bnz.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;

@Repository
public class UserDaoImpl implements UserDao, RowMapper<User> {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    //1. 转账
    @Override
    public void updateUser(int uid, double balance) {

        jdbcTemplate.update("update user set balance=balance+? where uid=?",balance,uid);
    }

    /**
     * 2. 添加用户
     * @param user
     */
    @Override
    public void add(User user) {
        jdbcTemplate.update("insert into user values (null,?,?)",user.getUsername(),user.getBalance());
    }

    /**
     * 3. 根据id查询用户
     * @param id
     * @return
     */
    @Override
    public User findById(int id) {
        return jdbcTemplate.queryForObject("select * from user where uid = ?",this,id);

    }

    /**
     * 4. 修改用户信息
     * @param user
     */
    @Override
    public void update(User user) {
        jdbcTemplate.update("update user set username = ?,balance = ? where uid = ?",user.getUsername(),user.getBalance(),user.getUid());
    }

    @Override
    public void delete(User user) {
        jdbcTemplate.update("delete from user where uid = ?",user.getUid());
    }

    @Override
    //实现行映射器（将ResultSet转换为User
    public User mapRow(ResultSet rs,int rowNum) throws SQLException {
        return  new User(rs.getInt("uid"),
                         rs.getString("username"),
                          rs.getDouble("balance"));
    }
}
